const { json } = require("express");
const db = require("../DBHelper");
class Register {
  async register(req, res) {
    let sql =
      "select id,username,password from users where status=1 and username=?";
    let params = [req.body.username];
    let pwd = req.body.password;
    let pwd1 = req.body.password1;
    let result = await db.exec(sql, params);
    let isLogin = result && result.length >= 1;
    if (params == "" || params == null) {
      res.json({ msg: "用户名不能为空!" });
    } else if (isLogin) {
      res.json({ msg: "用户名已存在!", code: -1 });
    } else if (pwd == "" || pwd == null) {
      res.json({ msg: "请输入密码!" });
    } else if (pwd1 != pwd) {
      res.json({ msg: "请输入相同密码!" });
    } else {
      let sql_insert = "insert into users (username,password) value(?,?);";
      let params = [req.body.username, req.body.password];
      let result = await db.exec(sql_insert, params);
      let isInsert = result && result.affectedRows >= 1;
      res.json({
        msg: isInsert ? "注册成功" : "注册失败",
        code: 1,
      });
    }
  }
}

module.exports = new Register();
